package com.crr.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;

@Component
@Slf4j//日志注解 通过log输出信息
public class RabbitUtils {
    ConcurrentSkipListMap sendMap = new ConcurrentSkipListMap();//存储发送的消息
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 异步确认发送消息
     *
     * @param msg
     */
    public void send1(String msg) {
        /**
         * 设置监听
         * 参数为回调函数 confirmCallback
         * 回调函数的参数void confirm(@Nullable CorrelationData var1, boolean var2, @Nullable String var3);
         *  参数说明 1相关数据 2是否成功投递 3
         */
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                //消息投递成功
                log.info("消息[" + sendMap.get(correlationData.getId()) + "]投递成功" + cause);
            } else {
                //消息投递失败
                log.info("消息[" + sendMap.get(correlationData.getId()) + "]投递失败" + cause);
            }
        });

        //发送数据
        String id = UUID.randomUUID().toString();
        //将消息与id关联
        sendMap.put(id, msg);
        rabbitTemplate.send("", "orderQueue", new Message(msg.getBytes()), new CorrelationData(id));

    }


    public void sendLazy(String msg) {
        MessageProperties mp = new MessageProperties();
        mp.setHeader("x-delay", 10000);//延迟10ms
        Message message = new Message(msg.getBytes(), mp);
        rabbitTemplate.send("lazy-ex", "lazy", message);
        System.out.println("消息已发送");
    }

}
